<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索和操作区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchEmpNum"
          placeholder="请输入员工编号"
          style="width: 200px"
          class="filter-item"
        />
        <el-button type="primary" icon="el-icon-search" @click="searchByEmpNum">
          搜索
        </el-button>
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">
          添加
        </el-button>
      </div>

      <!-- 表格部分 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
        <el-table-column prop="recordId" label="记录ID" width="80" align="center" />
        <el-table-column prop="empNum" label="员工编号" width="100" align="center" />
        <el-table-column prop="trainingName" label="培训名称" width="150" />
        <el-table-column prop="startDate" label="开始时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.startDate ? scope.row.startDate.substring(0, 16) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.endDate ? scope.row.endDate.substring(0, 16) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="trainingContent" label="培训内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="trainingResult" label="培训结果" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.trainingResult === '优秀' ? 'success' : 'info'">
              {{ scope.row.trainingResult }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="员工编号" prop="empNum">
          <el-input v-model="form.empNum" placeholder="请输入员工编号" />
        </el-form-item>
        <el-form-item label="培训名称" prop="trainingName">
          <el-input v-model="form.trainingName" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="培训内容" prop="trainingContent">
          <el-input
            type="textarea"
            v-model="form.trainingContent"
            :rows="3"
            placeholder="请输入培训内容"
          />
        </el-form-item>
        <el-form-item label="培训结果" prop="trainingResult">
          <el-select v-model="form.trainingResult" placeholder="请选择培训结果">
            <el-option label="优秀" value="优秀" />
            <el-option label="通过" value="通过" />
            <el-option label="未通过" value="未通过" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TrainingManage',
  data() {
    return {
      tableData: [],
      loading: false,
      searchEmpNum: '',
      dialogVisible: false,
      dialogTitle: '新增培训记录',
      isEdit: false,
      currentRecordId: null,
      form: {
        empNum: '',
        trainingName: '',
        startDate: '',
        endDate: '',
        trainingContent: '',
        trainingResult: ''
      },
      rules: {
        empNum: [{ required: true, message: '请输入员工编号', trigger: 'blur' }],
        trainingName: [{ required: true, message: '请输入培训名称', trigger: 'blur' }],
        startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        trainingContent: [{ required: true, message: '请输入培训内容', trigger: 'blur' }],
        trainingResult: [{ required: true, message: '请选择培训结果', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.$http.get('/api/training_records').then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data
        }
      }).finally(() => {
        this.loading = false
      })
    },

    searchByEmpNum() {
      if (!this.searchEmpNum) {
        this.getList()
        return
      }
      this.loading = true
      this.$http.get(`/api/training_records/${this.searchEmpNum}`).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data
        }
      }).finally(() => {
        this.loading = false
      })
    },

    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增培训记录'
      this.form = {
        empNum: '',
        trainingName: '',
        startDate: '',
        endDate: '',
        trainingContent: '',
        trainingResult: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑培训记录'
      this.currentRecordId = row.recordId
      this.form = { ...row }
      this.dialogVisible = true
    },

    handleClose() {
      this.$refs.form && this.$refs.form.resetFields();
      this.dialogVisible = false;
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const data = {
            empNum: parseInt(this.form.empNum),
            trainingName: this.form.trainingName,
            startDate: this.form.startDate,
            endDate: this.form.endDate,
            trainingContent: this.form.trainingContent,
            trainingResult: this.form.trainingResult
          }

          const config = {
            headers: {
              'Content-Type': 'application/json;charset=UTF-8'
            }
          }

          const request = this.isEdit
            ? this.$http.put(`/api/training_records/${this.currentRecordId}`, data, config)
            : this.$http.post('/api/training_records', data, config)

          request
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(this.isEdit ? '更新成功' : '添加成功')
                this.handleClose()
                this.getList()
              } else {
                this.$message.error(response.data.msg || (this.isEdit ? '更新失败' : '添加失败'))
              }
            })
            .catch(error => {
              this.$message.error(`操作失败: ${error.message}`)
            })
        }
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除该培训记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/training_records/${row.recordId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功')
              this.getList()
            } else {
              this.$message.error(response.data.msg)
            }
          })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.el-table {
  margin-top: 15px;
}

/* 添加操作按钮样式 */
.el-button + .el-button {
  margin-left: 5px;
}
</style>
